package com.reggie.console.convertor;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.model.PageDTO;

import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yth
 * @since 2023-06-11-0:54
 */
public class PageDTOConvertor {

    public static <T> PageDTO<T> convertModelToPageDTO(Page<T> page) {
        if (page == null) {
            throw new IllegalArgumentException();
        }
        PageDTO<T> vo = new PageDTO<>();
        vo.setRecords(page.getRecords());
        vo.setTotal(page.getTotal());
        vo.setCurrent(Math.toIntExact(page.getCurrent()));
        vo.setSize(Math.toIntExact(page.getSize()));
        return vo;
    }

    /**
     * 把mybatis-plus中的page对象转换成自定义的PageDTO对象
     */
    public static <S, T> PageDTO<T> convertModelToPageDTO(Page<S> page, Function<S, T> mapper) {
        if (page == null || mapper == null) {
            return null;
        }
        PageDTO<T> vo = new PageDTO<>();
        vo.setRecords(
                page.getRecords().stream()
                        .map(mapper)
                        .collect(Collectors.toList())
        );
        vo.setTotal(page.getTotal());
        vo.setCurrent(Math.toIntExact(page.getCurrent()));
        vo.setSize(Math.toIntExact(page.getSize()));
        return vo;
    }

    private PageDTOConvertor() {
        throw new AssertionError();
    }

}
